class IndexedDbUtil {
  static instance: IndexedDbUtil;

  static db: IDBDatabase;
  static request: IDBOpenDBRequest;

  static DbName = "zw-lowcode";
  static DbVersion = 1;

  constructor() {}

  static getInstance(): IndexedDbUtil {
    if (IndexedDbUtil.instance === undefined) {
      IndexedDbUtil.instance = new IndexedDbUtil();
      IndexedDbUtil.request = window.indexedDB.open(IndexedDbUtil.DbName, 1);
      IndexedDbUtil.request.onsuccess = (event) => {
        IndexedDbUtil.db = (event.target as IDBOpenDBRequest).result;
      };
      IndexedDbUtil.request.onerror = (event) => {
        console.error("为什么不允许我的 web 应用使用 IndexedDB！");
      };
    }
    return IndexedDbUtil.instance;
  }

  static getDb(): IDBDatabase {
    return IndexedDbUtil.db;
  }

  static getRequest(): IDBOpenDBRequest {
    return IndexedDbUtil.request;
  }

  getData(key: string): Promise<any> {
    return new Promise((resolve) => {
      IndexedDbUtil.db.transaction(IndexedDbUtil.DbName).objectStore("customers").get(key).onsuccess = (event) =>
        resolve((event.target as IDBRequest).result);
    });
  }

  createTable() {
    const request = window.indexedDB.open(IndexedDbUtil.DbName, 2);
    request.onupgradeneeded = (event) => {
      const customerData = [
        { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" },
        { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" },
      ];
      const objectStore = IndexedDbUtil.db.createObjectStore("customers", { keyPath: "ssn" });
      objectStore.transaction.oncomplete = (event) => {
        // 将数据保存到新创建的对象存储中。
        const customerObjectStore = IndexedDbUtil.db
          .transaction(IndexedDbUtil.DbName, "readwrite")
          .objectStore("customers");
        customerData.forEach((customer) => {
          customerObjectStore.add(customer);
        });
      };
    };
  }
}

export default IndexedDbUtil;
